package com.tmt.im.manager.service;

import com.alibaba.fastjson2.JSONObject;
import com.tmt.data.jpa.service.TmtJpaDataService;
import com.tmt.data.jpa.service.beans.SyncUserRoleDataResponse;
import com.tmt.data.jpa.service.beans.UserRoleInfoVo;
import com.tmt.im.common.enums.IMRoleEnum;
import com.tmt.im.jpa.entity.IMRole;
import com.tmt.im.jpa.entity.IMUser;
import com.tmt.im.jpa.entity.IMUserRole;
import com.tmt.im.jpa.entity.PersonalSetting;
import com.tmt.im.jpa.repository.IMRoleRepo;
import com.tmt.im.jpa.repository.IMUserRepo;
import com.tmt.im.jpa.repository.IMUserRoleRepo;
import com.tmt.im.jpa.repository.PersonalSettingRepo;
import com.tmt.im.manager.config.beans.DataSyncProperties;
import com.tmt.springboot.common.restful.ExecuteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Objects;

/**
 * @Description TODO
 * @Author wuyi
 * @Date 2024/9/20 11:53
 * @Version 1.0
 **/
@Slf4j
@Service
@Order(3)
public class IMUserRoleService extends TmtJpaDataService<IMUserRole, Long> {

    private final IMUserRoleRepo userRoleRepo;

    private final IMUserRepo userRepo;

    private final PersonalSettingRepo settingRepo;

    private final IMRoleRepo roleRepo;

    private final DataSyncProperties dataSyncProperties;

    public IMUserRoleService(IMUserRoleRepo mainRepo,
                             IMUserRepo userRepo,
                             PersonalSettingRepo settingRepo,
                             IMRoleRepo roleRepo,
                             DataSyncProperties dataSyncProperties) {
        super(mainRepo);
        this.userRoleRepo = mainRepo;
        this.userRepo = userRepo;
        this.settingRepo = settingRepo;
        this.roleRepo = roleRepo;
        this.dataSyncProperties = dataSyncProperties;
    }

    @Transactional(rollbackFor = Exception.class)
    public void InitializeTable() {
        try {
            log.info("----从授权服务器拉取用户角色列表----开始---");
            loadUserRoles();
            log.info("----从授权服务器拉取用户角色列表----结束---");
        } catch (Exception ex) {
            log.debug(ex.getMessage(), ex);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void loadUserRoles() {
        long pageIndex = 0;
        Long totalPageCount = null;

        JSONObject request = new JSONObject();
        request.put("pageIndex", pageIndex);
        request.put("pageSize", 50);
        request.put("clientId", null);

        while (totalPageCount == null || pageIndex < totalPageCount) {
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request);
            ParameterizedTypeReference<ExecuteResult<SyncUserRoleDataResponse>> responseType = new ParameterizedTypeReference<>() {
            };
            ResponseEntity<ExecuteResult<SyncUserRoleDataResponse>> jsonObjectResponseEntity =
                    new RestTemplate().exchange(dataSyncProperties.getUserRoleDataUrl(), HttpMethod.POST, entity, responseType);

            ExecuteResult<SyncUserRoleDataResponse> body = jsonObjectResponseEntity.getBody();
            assert body != null;
            if (body.getData() == null || CollectionUtils.isEmpty(body.getData().getUserRoleInfoVos())) {
                return;
            }
            try {
                for (UserRoleInfoVo vo : body.getData().getUserRoleInfoVos()) {
                    try {
                        IMUser user = userRepo.findById(vo.getUserId()).orElse(null);
                        assert user != null;
                        IMRole role = roleRepo.findById(vo.getRoleId()).orElse(null);
                        assert role != null;
                        IMUserRole userRole = userRoleRepo.findById(vo.getId()).orElse(null);
                        if (userRole != null) {
                            userRole.setUser(user);
                            userRole.setRole(role);
                        } else {
                            userRole = new IMUserRole();
                            userRole.setId(vo.getId());
                            userRole.setUser(user);
                            userRole.setRole(role);
                        }
                        userRoleRepo.save(userRole);

                        if (Objects.equals(role.getCode(), IMRoleEnum.IM_ROLE_CUSTOMER.name())) {
                            PersonalSetting setting = settingRepo.findById(user.getSettingId()).orElse(null);
                            if (setting != null) {
                                //默认将该用户的reviewOnAddingFriend设置为false,允许其他人加其为好友时不需要其同意。
                                setting.setReviewOnAddingFriend(false);
                                settingRepo.save(setting);
                            }
                        }

                    } catch (Exception ex) {
                        log.error("导入用户角色数据出现异常：{}", ex.getMessage());
                    }
                }
                if (totalPageCount == null) {
                    totalPageCount = body.getData().getTotalPages();
                }
                pageIndex++;
                request.put("pageIndex", pageIndex);
            } catch (Exception ex) {
                log.error("接口{}返回的数据格式异常:{}", dataSyncProperties.getUserRoleDataUrl(), body);
            }
        }

    }
}
